package rpcbiz

import (
	"net"
	"errors"
	"strconv"
	"cloud_worm/util/unet/rpc"
	"cloud_worm/access/server/client"
	"cloud_worm/util/unet"
	"cloud_worm/util/proto/urpc"
	"cloud_worm/util/uconst"
)

// --------------------- get all online status 操作 ---------------------
type AllOnlineArgs urpc.AllOnlineArgs
// StatusAbout.GetAllOnline 获取所有客户端的在线状态
func (s *StatusAbout) GetAllOnline(args *AllOnlineArgs, reply *urpc.AllOnlineReply) error {

	client.AgentPoolInst.Mux.Lock()
	for ip, value := range client.AgentPoolInst.IPMap {
		one := urpc.OneOnlineReply{
			IP: ip,
			Id: value.Id,
			Version: strconv.Itoa(value.Version),
			Pid: strconv.Itoa(value.Pid),
		}
		reply.Hosts = append(reply.Hosts, one)
	}
	client.AgentPoolInst.Mux.Unlock()

	return nil
}

// --------------------- get one online status 操作 ---------------------
type OneOnlineArgs urpc.OneOnlineArgs
func (args *OneOnlineArgs) param() error {
	if len(args.Id) != uconst.AgentIdLen {
		return errors.New("input worm id error")
	}
	return nil
}


// StatusAbout.GetOneOnline 获取单个客户端的状态
func (s *StatusAbout) GetOneOnline(args *OneOnlineArgs, reply *urpc.OneOnlineReply) error {
	err := args.param()
	if err != nil {
		return err
	}

	if client.AgentPoolInst.HaveConnByID(args.Id) == false {
		return urpc.NoOnlineAgentErr
	}

	agent := client.AgentPoolInst.GetAgentByID(args.Id)
	reply.IP = agent.IP
	reply.Id = agent.Id
	reply.Version = strconv.Itoa(agent.Version)
	reply.Pid = strconv.Itoa(agent.Pid)

	return nil
}

// --------------------- one ping 操作 ---------------------
type OnePingArgs urpc.OnePingArgs
// OnePingArgs.param 参数解析处理
func (args *OnePingArgs) param() error {
	if net.ParseIP(args.IP) == nil {
		return errors.New("input ip error")
	}
	return nil
}

// StatusAbout.DoOnePing 执行ping操作
func (s *StatusAbout) DoOnePing(args *OnePingArgs, reply *urpc.OnePingReply) error {

	err := args.param()
	if err != nil {
		return err
	}

	ok, err := unet.CheckIpOnline(args.IP)
	if err != nil {
		reply.IP = args.IP
		reply.Ok = false
		reply.Msg = err.Error()
	} else {
		reply.IP = args.IP
		reply.Ok = ok
	}

	return nil
}

type StatusAbout int

func init()  {
	rpc.Register(new(StatusAbout))
}
